<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Doit extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct()
	 {
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('Doit_m','m');
		$this->pageSize =$this->config->item('pagenum');
	 }

	
	/****************
	** 顺丰交运功能
	** 
	***************/
	public function sfexpress($pageid,$num)
	{
	
		$nowpage = $pageid;
	    if ($nowpage == "")
			$nowpage = 1;
		else
			$nowpage = $nowpage+1;
		 if ($num == "")$num = 0;
		$res = $this->m->getsfexpress($nowpage,$num);
		
		echo $res["str"];
		echo "22";
		echo "<meta http-equiv=\"refresh\" content=\"1; url=/doit/sfexpress/$nowpage/$res[num]\">";
		
	}
	public function ajaxbutton()
	{
		$op = $_REQUEST["op"];

		//更新马帮产品的三个产品信息
		if($op=="updatemabangproduct")
		{
			$this->load->library('Mabang');
			$ress = $this->mabang->updatemabangproduct();
			echo "OK";
			die;
		}

		/**********自动更新6个月当天的销售****每天晚上10点执行***/
		if($op == 'updatamabangstock')
		{
			$res = $this->fun->getdatabaseslist('p_product'," AND zhixiaotime is not null");
			$this->load->library('Mabang');
			foreach($res as $key=>$rs)
			{
				if(date("Y-m-d") == $rs["zhixiaotime"])	//如果滞销时间等于当前时间
				{
					$ress = $this->mabang->getskuname(trim($rs["sku"]));
					$stocknum = $ress[0]->SAVENUM;
					//计算滞销率
					$xiaoliang = $this->mabang->getsalessum(trim($rs["sku"]),6,$rs["tbopertime"]); //6个月的销量

					$this->db->query("UPDATE p_product SET zhixiaonum = '".$stocknum."',xiaoliang = '".$xiaoliang."' where id='".$rs["id"]."'");
					
				}
			}

			echo "OK";
		}


		/***********
		*** 导ubi
		*************/
		if($op =='inputubi')
		{
			require_once BASEPATH.'../fuman/ClassesExcel/PHPExcel/IOFactory.php';
			$upfile = BASEPATH."../fuman/Exceltemplate/ubi2.xlsx";
			if(!file_exists($upfile))
			{
				echo "没找到文件->". $upfile;
				die;
			}

			if($resExcel = PHPExcel_IOFactory::load($upfile)){
				$allRow = $resExcel->getActiveSheet()->getHighestRow();
				$s = 0;
				for($i=1;$i<=$allRow;++$i){
					$A=trim($resExcel->getActiveSheet()->getCell('A'.$i)->getValue());	//sku
					$B=trim($resExcel->getActiveSheet()->getCell('B'.$i)->getValue());	//sku
					
					$post="";
					$post['weight'] = $A* 1000;
					$post['price'] = $B;
					$this->db->insert("db_order_express_ubi",$post);
				}
			}
		}
		/**********************
		***	读取Excel文档，
		*** 更新工时，出厂价，批量价		
		********************************/
		if($op == 'inputexcel')
		{

			require_once BASEPATH.'../fuman/ClassesExcel/PHPExcel/IOFactory.php';
			$upfile = BASEPATH."../fuman/cangwei.xls";
			if(!file_exists($upfile))
			{
				echo "没找到文件->". $upfile;
				die;
			}
			$isok = $iserr = '';
			if($resExcel = PHPExcel_IOFactory::load($upfile)){
				$allRow = $resExcel->getActiveSheet()->getHighestRow();
				$s = 0;
				for($i=1;$i<=$allRow;++$i){
					$A=trim($resExcel->getActiveSheet()->getCell('A'.$i)->getValue());	//sku
					$B=trim($resExcel->getActiveSheet()->getCell('B'.$i)->getValue());	//sku
					
					$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".$A."'");
					if(!$rsdb)
					{
						$goodsno =  $A;
						//判断是否包含-
						$expgoodsno = explode("-",trim($goodsno));
						if(count($expgoodsno)>=2){
							$parent_goods = $expgoodsno[0];
						}else{
							$parent_goods = trim($goodsno);
						}
						echo $parent_goods;




						echo $s."->";
						echo $A;
						echo "<br>";
						$s=$s+1;
					}

					
					if($H)	//有信息则下架
					{
						echo "<hr>";
						$isok.=$A.",";
					}
			
				}
			}


			echo $isok;
			echo "<hr>";
			echo $iserr;
		}
		/**********************
		**
		** 将亚马逊订单生成PDF文档
		** 并且保存在本地
		**************************/
		if($op =='autosavePDF')
		{
		
			$rsdb = $this->fun->getdatabasesdetail("db_amzordertmp"," AND flag =1 ","amzorderid,id");
			if($rsdb){
				$wwwurl = "http://".$_SERVER["HTTP_HOST"]."/";
				$url = $wwwurl."doit/ajaxbutton?op=amazonOrderPDF&id={$rsdb[id]}&amzorderid={$rsdb[amzorderid]}";
				$Path = BASEPATH. "../uploads/amazonOrder/".$rsdb["amzorderid"].".pdf";
				if(file_exists($Path))
				{
					$this->db->update('db_amzordertmp',array("flag"=>2),"id='".$rsdb["id"]."'");
					echo "<meta http-equiv=\"refresh\" content=\"0; url=/doit/ajaxbutton?op=autosavePDF\">";	//执行插入商品信息
					die;				
				}else{
					$content=file_get_contents($url);//下载到内存
					if(file_put_contents($Path, $content))
					{
						$this->db->update('db_amzordertmp',array("flag"=>2),"id='".$rsdb["id"]."'");
						echo $rsdb["amzorderid"];
						echo "<meta http-equiv=\"refresh\" content=\"1; url=/doit/ajaxbutton?op=autosavePDF\">";	//执行插入商品信息
						die;
					}else{
						echo "出错";
						die;
					}
				}
			
			}
		}
		
		if($op =='Proudctsavetofuman')
		{
			//将新品保存到原复漫
			$this->load->library('Fshop');
			$rsdb = $this->db->get_where('db_product_develop',"status=6")->result_array();
			foreach($rsdb as $key=>$rs)
			{
				$this->fshop->insertFshopProduct($rs['id']);	//更新马帮里面所有的店铺到系统f_shop表
			}
		}

		if($op =='amazonOrderPDF')
		{
			require_once BASEPATH.'../fuman/phppdf/tcpdf.php';
			$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			$id = $this->input->get('id');
			$amzorderid = $this->input->get('amzorderid');
			$wwwurl = "http://".$_SERVER["HTTP_HOST"]."/";
			$url = $wwwurl."doit/ajaxbutton?op=printorder&id=".$id;
			
			$cookie_jar = '';
			$header = array('Content-Type:text/html;charset=UTF-8');
			$postdata = $this->fun->curlfunc($url,"",$cookie_jar,$header);
			// set document information
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetSubject(' Zuggi GmbH');
			$pdf->SetKeywords(' Zuggi GmbH');
			$pdf->setPrintHeader(false);
			$pdf->setPrintFooter(false);
			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
			// set margins
			$pdf->SetMargins(5, 5, 5);
			//$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
			//$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
			// ---------------------------------------------------------
			// set font
			$pdf->SetFont('dejavusans', '', 10);
			// add a page
			$pdf->AddPage();
			$pdf->writeHTML($postdata, true, false, true, false, '');
			$pdf->Output($amzorderid.'.pdf', 'I');
		
			
		}
		/**********************
		**
		** 将亚马逊订单生成PDF文档
		** 生成需要用到的html文档
		****************************/
		if($op=='printorder')
		{
			$id = intval($this->input->get('id'));
			$rsdb = $this->fun->getdatabasesdetail("db_amzordertmp"," AND id = '".$id."'");
			if($rsdb)
			{
					$rsdb["origintotle"] = str_replace(".", ",", $rsdb["origintotle"]);
				if($rsdb["ordercreatetime"]>'2016-04-04 00:00:00')
				{
					$this->tpl->assign("si",1);
				}else{
					$this->tpl->assign("si",2);
				}
				$resell = $this->db->get_where('db_amzordertmpsell',"ordertmpid='".$id."'")->result_array();
				$shipprice=0;
				$giftwrapprice = 0;
				$promotionDiscount = 0;
				foreach($resell as $key=>$rs)
				{
					$resell[$key]["amount"] = str_replace(".", ",", $rs["amount"]);
					$resell[$key]["sellprice"] = str_replace(".", ",", $rs["sellprice"]);
					$allshipprice =$shipprice + $rs["shipprice"];
					if($allshipprice==0)
						$allshipprice = "0,00";
					else
						$allshipprice= str_replace(".", ",", $allshipprice);
					$allgiftwrapprice =$giftwrapprice + $rs["giftwrapprice"];
					if($allgiftwrapprice==0)$allgiftwrapprice = "0,00";
					else
					$allgiftwrapprice= str_replace(".", ",", $allgiftwrapprice);
					$promotionDiscount =$promotionDiscount + $rs["promotionDiscount"];
					if($promotionDiscount==0){
						$promotionDiscount = "0,00";
					}
					else{
						$promotionDiscount = "-".$promotionDiscount;
						$promotionDiscount= str_replace(".", ",", $promotionDiscount);
					}
				}
				$this->tpl->assign("allshipprice",$allshipprice);
				$this->tpl->assign("allgiftwrapprice",$allgiftwrapprice);
				$this->tpl->assign("promotionDiscount",$promotionDiscount);
				$this->tpl->assign("resell",$resell);
				$this->tpl->assign("rsdb",$rsdb);
				$this->tpl->assign("Nettosumme",str_replace(".", ",", round($rsdb["origintotle"]/1.19,2)));
				$this->tpl->assign("MwSt",str_replace(".", ",", round(($rsdb["origintotle"]/1.19)*0.19,2)));
				$this->tpl->display("order/amazonOrderPDF.tpl",'','',1);
			}

		}
		
		
		/*********处理系统消息****************/
		if($op =='domessage')
		{
			$id=intval($this->input->post('ID'));
			$rsdb = $this->fun->getdatabasesdetail('db_message'," AND id='".$id."'");
			if($rsdb["isread"]>0){
				$this->db->update('db_message', array("isshow"=>1), " message_toID ='".$_COOKIE["userid"]."'");	//只有大于0的时候才进行更新，为0时表示所有人都需要手工点击查看消息
			}
			$post['message_id'] = $id;
			$post['isread'] = 1;
			$post['readtime'] = date("Y-m-d H:i:s");
			$post['userid'] = $_COOKIE["userid"];
			$res = $this->db->query($this->db->insert_string('db_message_read', $post));
			echo json_encode($rsdb);
			die;
		}
		/****五位工厂均码SKU，如果遇到下架或者停产，直接换成8位SKU***/
		if($op =='Autoinsertordertofactory')
		{
			$this->load->library('Stockwarning');
			$ress = $this->stockwarning->autochangsku();
		}
		/****从新系统导订单到工厂系统，***/
		if($op =='AutoinsertordertofactoryPro')
		{
			
			$res = $this->m->autoinsertordertofactory();
			
			
		}
		/****自动获取192.168.1.50图片系统的图片***/
		if($op =='AutoInsertImagesTo')
		{
			$res = $this->m->AutoInsertImagesTo();
			$res = $this->m->AutoInsertImagestoexternalBuyPro();
		}
		
		/***********自动读取老复漫系统的新开发产品到系统***********************/
		if($op =='AutoInsertnewproduct')
		{
			$this->load->library('Fshop');
			$this->fshop->getfumannewprodct();
		}
//		/********测试****可删除****/
		if($op =='autoInsertErrProudct')
		{
			$this->load->library('Mabang');
			$res = $this->mabang->autoInsertErrProudct(1);
		}

		/*******************************
		*** 更新图片信息
		*** 判断/uploads/systemImages目录下是否美工上传新的图片，存在就即保存并生成缩略图
		*** 需要定时执行，以方便新的商品处理图片功能
		******************************/
		if($op =='autoinsertImages')
		{
			$filename = dirname(__FILE__).'/../../uploads/islock.txt';
			$path =dirname(__FILE__).'/../../';
			$path2 = "uploads/systemImages/";
			if (file_exists($filename)) {
				$goodsID = file_get_contents($filename);
			} else {
				 $goodsID = 0;
				 $this->fun->write_file($filename, $goodsID);
			}
			$this->db->order_by('goods_id', 'ASC');
			$goodslist = $this->db->get_where('db_goods'," goods_id >{$goodsID}")->result_array();
			foreach($goodslist as $key=>$rs)
			{
				$rsdb = $this->fun->getdatabasesdetail("db_goods_images"," AND goods_id='".$rs["goods_id"]."'");
				if($rsdb)
				{
					continue;
				}
				for($i=1;$i<=3;$i++){
					$imgpath = $path.$path2.$rs["goods_parent_sku"]."_{$i}.jpg";
					if (file_exists($imgpath)) {
						$filenamest = basename($imgpath);	//文件名
						$filesize = round(filesize($imgpath)/1024,2)."kb";//文件大小
						$filesta = explode(".",$filenamest);
						$filetype = $filesta[1];
						
						//处理缩略图
						$upload_path_thumbnail = '/uploads/thumbnail/'.date("Ymd")."";
						$dirthumb = dirname(__FILE__) . "/../..".$upload_path_thumbnail;
						!is_dir($dirthumb) && @mkdir($dirthumb, 0755, true);
						
						$this->load->library('image_lib');
						$configimg['image_library'] = 'gd2';
						$configimg['source_image'] =$imgpath;
						$configimg['create_thumb'] = TRUE;
						$configimg['maintain_ratio'] = TRUE;
						$configimg['new_image'] =  $dirthumb."/". $filesta[0]."." . $filetype;
						$configimg['width']     = $this->config->item('resizeToWidth');
						$configimg['height']   = $this->config->item('resizeToHeight');
						$this->image_lib->initialize($configimg);
						if ( ! $this->image_lib->resize())
						{
							echo $this->image_lib->display_errors();
						}else{
							$this->image_lib->clear();
						}
						
						$postdata = "";
						$postdata["goods_id"] = $rs["goods_id"];
						$postdata["images_type"] = 1;
						$postdata["images_url"] = $path2.$rs["goods_parent_sku"]."_{$i}.jpg";
						$postdata["local_url"] = $path2.$rs["goods_parent_sku"]."_{$i}.jpg";
						$postdata["thumb_url"] = $upload_path_thumbnail."/". $filesta[0]."_thumb." . $filetype;
						$postdata["filename"] = $filenamest;
						$postdata["filesize"] = $filesize;
						$postdata["createUser"] = '刘祥';
						$postdata["instime"] = time();
						
						$this->db->insert("db_goods_images",$postdata);
						
					}

				}

				 //$this->fun->write_file($filename,$rs["goods_id"]);
				 $this->fun->write_file($filename,0);//设置成为0，每天重复跑一次
			}
		}
		/*****定时更新海外仓产品的价格信息********/
		if($op =='overseaproduct_price')
		{
			$goodslist =  $this->db->select('sku,costprice,id')->get("t_overseaproduct")->result_array();
			foreach($goodslist as $key=>$rs)
			{
				$rsdb = $this->fun->getdatabasesdetail("db_goods", " AND goods_sku = '".$rs['sku']."'","g_costprice,bulkprice");
				if($rsdb)
				{
					
					if($rsdb['g_costprice'] != $rs['costprice'])
					{
						if($rsdb['bulkprice']>0)
						{
							$price = $rsdb['bulkprice'];
						}else{
							$price = $rsdb['g_costprice'];
						}
						$this->db->query($this->db->update_string("t_overseaproduct",array('costprice'=>$price)," id='".$rs['id']."'"));
					}
				}
			}
			echo "OK";
			die;
		}
		
		if($op =='amazonFba')
		{

			$totalamount = 0;
			$orderlist = $this->db->get_where('db_amzordertmp'," shopid is null")->result_array();
			foreach($orderlist as $key=>$rs)
			{
				$postdata="";
				$rshop = $this->fun->getdatabasesdetail("d_shop"," and name='".$rs["shopname"]."'");
				if($rshop)
				{
					$postdata["shopname"] = $rshop["name"];
					$postdata["shopid"] = $rshop["id"];
					$this->db->query( $this->db->update_string('db_amzordertmp',$postdata," id='".$rs['id']."'"));
					
				}
				
			}
			echo "OK";
			die;
		
			
		}
		
		/*******************************
		批量更新所有发货订单的商品重量
		20170912 偶尔使用一次
		*************/
		if($op =='setorderweigth')
		{
			$orderlist = $this->fun->getdatabaseslist("db_order_batchexpress"," and skuNum =1","*","group by skulist order by id DESC");
			$post="";
			foreach($orderlist as $key=>$rs)
			{
				$goods = $rs['skulist'];
				$batch_orderweight = round($rs['batch_orderweight']);
				
				$post[$key]['g_weight'] =$batch_orderweight;
				$post[$key]['goods_sku'] =$goods;

				echo $goods."->".$batch_orderweight;
				echo "<br>";
			}
		
			$this->db->update_batch('db_goods', $post, 'goods_sku');//批量更新

		}

		/*******************************
		批量更新所有商品的创建时间
		20170914 偶尔使用一次
		*************/
		if($op =='updateproducttime')
		{
			$orderlist = $this->fun->getdatabaseslist("db_goods_log"," AND types =  1 and (content LIKE '%添加新商品%' or content like '%Excel导入%' )","*"," order by id DESC");
			$post="";
			foreach($orderlist as $key=>$rs)
			{
				$post="";
				$post["g_updatetime"] = $rs['updatetime'];
				echo $this->db->update("db_goods",$post,"goods_id='".$rs['goods_id']."'");
				echo "<br>";
			}
		
			//$this->db->update_batch('db_goods', $post, 'goods_sku');//批量更新

		}
		
		/*******************************
		将定制的SKU库存清0
		20170914 偶尔使用一次
		*************/
		if($op =='testupdateproducttime')
		{
			$orderlist = $this->fun->getdatabaseslist("db_goods S","  AND (locate(11,S.goods_sku)=1 or locate(12,S.goods_sku)=1 ) and length(S.goods_sku)=8 ","goods_sku,goods_id"," order by goods_id DESC");
			$post="";
			foreach($orderlist as $key=>$rs)
			{
				if($this->fun->getfactorygoodsku($rs["goods_sku"]))
				{
					echo $this->db->update('db_goods_stock',array("stock"=>0)," goods_id='".$rs['goods_id']."'");
					echo"->";

				echo $rs["goods_sku"];
				echo "<br>";
				}
			}
		}
		if($op =='listestes')
		{
			$orderlist = $this->fun->getdatabaseslist("db_amzordertmp"," AND dates='1970-01-01'");
			foreach($orderlist as $key=>$rs)
			{
				$orts=strtotime($rs['ordercreatetime']);
				$dates = date("Y-m-d",$orts);
				echo $this->db->update('db_amzordertmp',array("dates"=>$dates),"id='".$rs['id']."'");
				echo "<br>";
			}
		}

		
		
		/**********************
		**
		** 列出所以可发货订单
		**************************/
		if($op =='issendokorder')
		{
			$orderlist = $this->fun->getdatabaseslist("db_order_list"," AND (order_status = 2 or order_status=3) AND shipping_status = 5 and is_nodelivery=0");
			foreach($orderlist as $key=>$order)
			{
				$isok = 1;
				$sell = $this->fun->getdatabaseslist("db_order_sell "," AND order_id='".$order['order_id']."'","goods_id,order_id");
				foreach($sell as $rs)
				{
					$rsdb = $this->fun->getdatabasesdetail("db_goods_stock"," AND  stock >0 and storage_id = 1 AND goods_id = '".$rs['goods_id']."'");
					if(!$rsdb)
					{
						$isok =0;
						continue;
					}
				}
				if($isok==1)
				{
					echo $order['order_sn'];
					echo "<br>";
				}
			}

		}
		if($op =='changcosprice')
		{
			//清仓的商品修改半价成本
			//$sku = "131474,132853-S,17599-L,18041-L,19463M-S,19588F-XS,19791F-S,19791M-S,19792M-XL,19794F-S,19794F-XL,19794F-XS,19853F-M,19894F-M,19894F-S,132852-S,132853-XL,16996-L,17491-L,17541-L,17765-L,19006-XL,19081F-M,19081F-S,19092F-L,19092F-S,19098F-S,19109F-S,19120F-M,19120F-S,19120F-XS,19142F-L,19143F-L,19143F-S,19143F-XS,19155F-XS,19194F-S,19194F-XS,19223F-XL,19226F-S,19226F-XS,19226M-L,19226M-XXL,19412F-M,19412F-XXL,19436F-S,19436F-XS,19436M-XS,19436M-XXL,19467F-S,19479F-XL,19479F-XS,19479M-L,19479M-M,19479M-S,19479M-XL,19498F-L,19513F-M,19537F-S,19592F-S,19592F-XS,19593F-S,19593F-XL,19593F-XS,19624F-L,19624F-S,19643F-XL,19764F-S,19764F-XS,19791F-XS,19791M-XXL,19792F-XS,19795F-S,19795F-XS,19808F-S,19808F-XL,19832F-XS,19833F-L,19833F-M,19833F-S,19833F-XS,19859F-L,19859F-M,19859F-S,19859F-XS,19885F-S,19894F-M,19894F-S,19913F-XS,19913M-S,19005-L,19005-XL,19948F-S";
			//$skulist = explode(",",$sku);
			$factorycode = $this->fun->factorycode();
			foreach($skulist as $key=>$rs)
			{
				$rsGoods = $this->db->get_one("SELECT goods_id,goods_sku,g_sale_status,g_costprice,bulkprice,goods_parent_sku from db_goods  where goods_sku = '".$rs."' and g_sale_status in(4,5,7)");
				$goodscodes  = substr($rsGoods["goods_parent_sku"],0,2);//取开头2位数
				if(is_numeric($rsGoods["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rsGoods["goods_parent_sku"]) && in_array($goodscodes,$factorycode))	//数字并且8位SKU并且11 12开头
				{
					if($rsGoods["bulkprice"]==0)
					{
						$rsdb = $this->db->get_one("select * from db_goods where goods_parent_sku = '".$rsGoods['goods_parent_sku']."' AND bulkprice >0 ");
						if($rsdb)
						{
							$bulkprice = $rsdb["bulkprice"];
						}else{
							$bulkprice = $rsdb["g_costprice"];
						}
					}else{
						$bulkprice = $rsGoods["bulkprice"];
					}
					//工厂
					$costprice = round($bulkprice / 2);
					echo $this->db->update("db_goods",array("bulkprice"=>$costprice),"goods_id=".$rsGoods["goods_id"]);
					echo "->".$costprice."->".$bulkprice;
					echo "<br>";
					$content= "半价清仓 原关联价[$bulkprice],修改成[$costprice]";
					$this->fun->goods_update_log($rsGoods["goods_id"],$content,1);
				}else{
					//普通
					if(!$rsGoods["goods_id"])
					{
						echo $rs;
						echo "<br>";
					}
					$g_costprice = $rsGoods["g_costprice"];
					$costprice = round($g_costprice / 2);
					echo $this->db->update("db_goods",array("g_costprice"=>$costprice),"goods_id=".$rsGoods["goods_id"]);
					echo "->".$costprice."->".$costprice;
					echo "<br>";
					$content= "半价清仓 原成本价[$g_costprice],修改成[$costprice]";
					$this->fun->goods_update_log($rsGoods["goods_id"],$content,1);
				}
				
			}
			print_r($skulist);

		}
		
		if($op =='checkamazon')
		{
			$this->load->library('AmazondataPro');
			$ress = $this->amazondatapro->checkAmazonOrder();
		}
		/****将所有的下架产品改成暂停销售状态*****/
		if($op =='getsalestatus')
		{
			/******子SKU清仓，主SKU停售，但又盘点了库存出来，需要清仓,将停售改成清仓状态*********/
			$goodslist = $this->fun->getdatabaseslist(' db_goods A left join db_goods_stock B on A.goods_id  = B.goods_id LEFT JOIN db_goods_parent C on A.goods_parentID = C.p_parent_id'," AND B.storage_id in(1,2) and B.stock>0 and A.g_sale_status =5 AND C.p_sale_status = 4"," A.*");
			if(count($goodslist)>0){
				foreach($goodslist as $key=>$goods)
				{
					$this->db->update('db_goods_parent',array("p_yz"=>0,"p_sale_status"=>5),"p_parent_id=".$goods['goods_parentID']);//从停售改成清仓
					$this->db->update('db_goods',array("yz"=>0),"goods_id=".$goods['goods_id']);//从停售改成清仓
				}
			}


	
			/******将所有标了停产的商品，如果有库存改成清仓*********/
			$res = $this->fun->getdatabaseslist("db_goods A LEFT JOIN db_goods_stock B ON A.goods_id  = B.goods_id "," AND g_sale_status=4 AND storage_id in(1,2)  ","A.goods_id,A.goods_sku,A.goods_name,A.goods_parentID,goods_parent_sku, SUM(stock)as stocks,positions,storage_name","group by `goods_id` having stocks>1");
			if(count($res)>0){
				foreach($res as $key=>$goods)
				{
						$this->db->update('db_goods',array("yz"=>0,'g_sale_status'=>5),"goods_id=".$goods['goods_id']);
						$this->db->update('db_goods_parent',array("p_yz"=>0,'p_sale_status'=>5),"p_parent_id=".$goods['goods_parentID']);
						$rval ="原停售商品盘点出新的库存,系统自动标清仓状态";
						$this->fun->goods_update_log($goods["goods_id"],$rval,1,0,0,'SYSTEM');	//更新商品信息
							$rsclear = $this->fun->getdatabasesdetail('db_goods_clear_list'," AND goods_id='".$goods["goods_id"]."'");
							if(!$rsclear){
								$post="";
								$post["parent_id"] = $goods["goods_parentID"];
								$post["goods_id"] = $goods["goods_id"];
								$post["goods_sku"] = $goods["goods_sku"];
								$post["goods_name"] = $goods['goods_name'];
								$post["positions"] = $goods['positions'];
								$post["storage_name"] = $goods['storage_name'];
								$post["stock"] = $goods['stock'];
								$post["types"] = 0;
								$post["oper"] = 'SYSTEM';
								$post["uptime"] = time();
								$this->db->insert("db_goods_clear_list",$post);
							}


						$this->fun->insertsysstatistical('status',5,$goods['goods_id'],0);	//设置清仓提醒
				}
			}
			
			
		
			/******************清仓的商品，如果库存清光了，自动改成停售*****************/
			$list = $this->fun->getdatabaseslist("db_goods A LEFT JOIN db_goods_stock B ON A.goods_id  = B.goods_id "," AND g_sale_status=5 AND storage_id in(1,2) ","A.goods_id,A.goods_parentID,goods_parent_sku, SUM(stock)as stocks"," group by `goods_id` having stocks <=0");
			if(count($list) >0)
			{
				foreach($list as $key=>$rs)
				{
						$this->db->update('db_goods',array("yz"=>2,"g_sale_status"=>4), 'goods_id=' . $rs['goods_id']);//SKU停售
						$this->fun->insertsysstatistical('status',4,$rs['goods_id'],0);	//设置清仓提醒
						$rval ="原清仓商品清仓完成,系统自动标停售";
						$this->fun->goods_update_log($rs["goods_id"],$rval,1,0,0,'SYSTEM');	//更新商品信息
				}
			}

			
		
			//判断停售的产品所有子商品都停售了，主商品也修改状态
			$list = $this->fun->getdatabaseslist("db_goods_parent"," AND p_parent_id not in(SELECT goods_parentID from db_goods where goods_parentID = db_goods_parent.p_parent_id and  g_sale_status in(1,2,3,5,6) ) AND p_yz = 0 ","p_parent_id");
			foreach($list as $key=>$rs)
			{
				$p_parent_id  =$rs["p_parent_id"];
				 $this->db->update("db_goods_parent",array("p_yz"=>2,"p_sale_status"=>4)," p_parent_id=".$p_parent_id);
			}
		
			/******************新品超过1个月自动改成正常销售*****************************/
			$list = $this->fun->getdatabaseslist("db_goods_parent"," AND p_sale_status = 1 ","p_parent_id,p_updatetime");
			if(count($list) >0)
			{
				foreach($list as $key=>$rs)
				{
					$times = strtotime($rs['p_updatetime']) +60*86400;
					if(time()-$times>0)
					{
						$this->db->update("db_goods_parent",array("p_sale_status"=>2)," p_parent_id=".$rs['p_parent_id']);
						$this->db->update("db_goods",array("g_sale_status"=>2)," goods_parentID=".$rs['p_parent_id']);
					}
				}
			}

			//自动处理商品信息 1清仓的商品，如果没有库存了并且待发为0，自动改成停售，并且添加进系统提示 2、新品超过2个月了自动改成正常销售 、3

			echo "OK";
		}
		if($op =='stockreset')
		{
			//库存负数的自动复位
			$list = $this->db->get_where("db_goods_stock"," stock <0  and storage_id = 1")->result_array();
			if(count($list) >0)
			{
				foreach($list as $key=>$rs)
				{
					$goods_id = $rs["goods_id"];
					$content="[{$rs[storage_name]}] 负库存清零 原库存 {$rs[stock]},修改成 0";
					$this->fun->goods_update_log($goods_id,$content,1);
					$this->db->update("db_goods_stock",array("stock"=>0)," id = ".$rs['id']);
				}
			}
			echo "OK";
		}
		if($op =='UpdateAmazonProductPro')	
		{
			$this->load->library('AmazondataPro');
			$ress = $this->amazondatapro->UpdateAmazonProductPro();
			if($ress == false)	//执行完成
			{
				echo "OK";
				die;
			}
		}
		//自动获取订单的预估运费
		if($op =='autoorderexpress')
		{
			$ordersn = $this->input->get_post('ordersn');
			$this->load->library('Orderexpress');
			$ress = $this->orderexpress->getexpressorderlist($ordersn);
		}
		if($op=='test')
		{
			$this->load->library('Magentodata');
			$this->magentodata->updatemagentwebdata();
			die;
			//重新计算成本
			$rsdb = $this->db->get_where("db_order_sell","goods_id>0 and costprice = 0")->result_array();
			foreach($rsdb as $key=>$goods)
			{
				$costprice = $this->fun->get_Goods_costprice($goods["goods_sn"]);//获取商品成本
				if($costprice>0)
				{
					echo $costprice;echo "->";
					echo $goods["goods_id"];echo "->";
					echo $goods["goods_sn"];
					echo "<br>";
					$post="";
					$post["costprice"] = $costprice;
					$this->db->update("db_order_sell",$post,"rec_id='".$goods['rec_id']."'");
					echo $this->db->last_query();
				}
			}
			echo count($rsdb);

			die;
			/**********高菲菲产品，鞋子，不包含44开头的SKU***********/
			$rsdb = $this->db->select('goods_sku,goods_id,g_buyer,g_checkman,goods_name')->get_where("db_goods","  (goods_name like '%鞋%' or goods_name like '%靴%') and locate('44',goods_sku)=0 and locate('4',goods_sku)=1")->result_array();
			$post="";
			foreach($rsdb as $key=>$rs)
			{
				$post[$key]["g_buyer"] = "高菲菲";
				$post[$key]["g_checkman"] = "高菲菲";
				$post[$key]["goods_id"] = $rs["goods_id"];
			}
			$this->db->update_batch('db_goods', $post, 'goods_id');//批量更新

			print_r($rsdb);
			die;


		
			$rsdb = $this->db->get_where("db_order_list","platformID=0")->result_array();
			foreach($rsdb as $key=>$order)
			{
				$arr_order_list="";
				$rsshop=$this->fun->getdatabasesdetail("d_shop", " AND id = '".$order["shopid"]."'");
				$arr_order_list['platformID']  = $rsshop['platfrom'];//平台
				$exchange=$this->fun->getdatabasesdetail("d_moneyrate"," and name='".$order["moneytype"]."'");
				$arr_order_list['moneyrate']  = $exchange["rate"];//汇率
				$this->db->update("db_order_list",$arr_order_list,"order_id = '".$order['order_id']."'");
				

			}
			echo "OK";
			echo count($rsdb);
			die;

			//
			$resbactionGoods = $this->fun->getdatabaseslist("db_order_batchexpress"," AND skulist='15037-M' AND skuNum=1",'id'," ORDER BY id DESC LIMIT 10 ");
			$nums =count($resbactionGoods);
			if($nums>0)
			{
				$bactorderID="";
				foreach($resbactionGoods as $sor)
				{
					$bactorderID[]= $sor['id'];
				}
				$bactorderID  = implode(",",$bactorderID);
				$rsdbWeth = $this->db->get_one("select sum(batch_orderweight) as weigth  from db_order_batchexpress where id in($bactorderID)");
				$weigth = $rsdbWeth["weigth"];
				echo $weigth;

				$junweith = intval($weigth/$nums);
				echo $junweith;
				
			}

			die;



				$this->load->library('Mabang');
				 $this->mabang->getselltop200();
				die;

			$pathpdf = dirname(__FILE__) . "/../..";
			$pdf = "/uploads/dhlexpress/20170727/3887032590-order.pdf";
			$pdf=$pathpdf.$pdf;
			$this->fun->testpdf2png($pdf);
			die;
			$this->load->library('Mabang');
			$this->mabang->insertMabangProduct(13);	//更新马帮里面所有的店铺到系统d_shop表

			die;
			$rsdb = $this->fun->getdatabasesdetail("db_order_list", " AND shipping_number = 'LW572054015CN'");
			$orderweightst =98;
			$freigth = $this->fun->get_Estimate_freight($orderweightst,$rsdb["country_cn"],0,'E邮宝');//重新计算预估运费
			echo $freigth;
			die;
			phpinfo();
			die;
		
			$where = " AND B.status = 3 AND B.finshtime>='2017-05-24 00:00:00'";
			$if_csv = 1;
			$list = $this->fun->getalllist("db_factory_sell A LEFT JOIN db_factory_order B ON A.orderId=B.id LEFT JOIN db_goods C ON A.goods_sku= C.goods_sku", $where, $nowpage, $if_csv, 200, $orderby,"A.*,B.orderId as ordernumber,B.finshtime,B.money,B.orderTime,B.shopmenttime,B.mabangorderid,B.factoryId,C.g_costprice,C.goods_name,C.goods_id");
			foreach($list["list"] as $rs)
			{
				 $shipingfee= $rs["scale"] * 100;
				//利润率计算
				if($rs["money"]>0){
					$amount =($rs["money"]*0.835) - $shipingfee;
					if($amount !=0){
						$lv = ($amount - $rs["g_costprice"]) / $amount;
						 $lv  = round($lv,3);
					}else{
						 $lv  = 0;
					}
				}else{
					 $lv = 0;
				}
					echo $lv;
					echo "<br>";echo $rs["orderId"];
					$this->db->query("UPDATE db_factory_sell SET rate ='".$lv."' where id= '".$rs["id"]."'");
				
			}
			//echo count($list["list"]);
			die;
			
		}

		/*******************************
		*** 定时读取远程123上亚马逊订单
		******************************/
		if($op =='getamazonOrderlist')
		{
			$this->load->library('Amazondata');
			$ress = $this->amazondata->getlist();
		}
		/*******************************
		*** 定时读取远程123上亚马逊订单
		******************************/
		if($op =='getinsertorderlist')
		{
			$this->load->library('Amazondata');
			$ress = $this->amazondata->getinsertorderlist();
		}
		/*******************************
		*** 自动交运UPS
		******************************/
		if($op =='upsexpress')
		{
			$res = $this->m->getupsexpress();
			echo $res["str"];
			echo "<meta http-equiv=\"refresh\" content=\"1; url=/doit/ajaxbutton?op=upsexpress\">";
		}
		
		/**************************
		**缺某些尺码的SKU，从马帮导入
		*************************/
		if($op =='mabangskuto')
		{
			$this->load->library('Fshop');
			//外采购的SKU
			$this->fshop->getMabangchima();
			die;
			/*************8位和5位关联SKU**********/
			
			$this->fshop->getallproduct();
		}

		/**********************
x		** 读取以前商品的关联信息
		**************************/
		if($op =='getlinkproduct')
		{
			$this->load->library('Fshop');
			//外采购的SKU
			$this->fshop->getlinkproduct();
			die;

		}

		if($op =='searchlinkproduct')
		{
			$sql = "SELECT goods_id,goods_sku,goods_parent_sku from db_goods where  length(goods_parent_sku)=8 AND (locate(11,goods_parent_sku)=1 or locate(12,goods_parent_sku)=1 ) and  goods_sku REGEXP '-'  ";
			$query = $this->db->query($sql);
			$dates = $query->result_array();
			foreach($dates as $key=>$rs)
			{
				$rsdb= $this->fun->getdatabasesdetail("db_goods_attr"," AND goods_id ='".$rs['goods_id']."' AND attr_value !=''");
			
				if(!$rsdb)
				{
					echo $rs['goods_parent_sku'];
					echo "<br>";
				}
			}
		}

		if($op =='TestYIDAtracking')
		{
			$tracking_number = trim($this->input->get('sn'));
			if($tracking_number)
			{
				$this->load->library('Expresssend');
				$back=$this->expresssend->getYIDAgettrack($tracking_number,'Test'); 
			}

		}

		//赞助订单已完货时发送邮件
		if($op =="SendZangzhuMail")
		{
			$this->load->library('AmazondataPro');
			$ress = $this->amazondatapro->savezangzhuorder();
			
		}


	}


}
